import Vue from "vue";
import Cookies from "js-cookie";
import Element from "element-ui";
import "normalize.css/normalize.css"; // a modern alternative to CSS resets
import "@/icons"; // icon
import "@/styles/element-variables.scss";
import "@/styles/index.scss"; // global css
import "@/utils/error-log"; // error log
Vue.use(Element, {
  size: Cookies.get("size") || "small" // set element-ui default size
});
// TODO 组件区域
// 自定义控制dialog
import Dialog from "@/components/dialog/index.vue";
Vue.component("el-dialog", Dialog);
// 自定义控制cascader，为了满足产品经理提出的需求，选择即关闭
import Cascader from "@/components/cascader/index.vue";
Vue.component("el-cascader", Cascader);
// 自定义控制date-picker，处理使用value-format或者value情况下的报错问题
import DatePicker from "@/components/datePicker/index.vue";
Vue.component("el-date-picker", DatePicker);
// print组件区域
import Print from "@/components/Print/print";
Vue.use(Print);
// TODO filter
import * as filters from "./filters"; // global filters
// register global utility filters
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key]);
});
// TODO 部分绑定到原型上的方法
// 编码
Vue.prototype.$encode = str => {
  return window.encodeURIComponent(str);
};
// 解码
Vue.prototype.$decode = str => {
  return window.decodeURIComponent(str);
};
// 日期格式化
Vue.prototype.$dateFormat = param => {
  let { time = "", format = "yyyy-MM-dd" } = param; // eslint-disable-line
  const _this = new Date(time);
  const o = {
    "M+": _this.getMonth() + 1, // 月份
    "d+": _this.getDate(), // 日
    "h+": _this.getHours(), // 小时
    "m+": _this.getMinutes(), // 分
    "s+": _this.getSeconds(), // 秒
    "q+": Math.floor((_this.getMonth() + 3) / 3), // 季度
    S: _this.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      (_this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return format;
};
// 下载方法
Vue.prototype.$downloadFunc = param => {
  const { method = "get", url = "", data = {}} = param;
  let str = "";
  for (const key in data) {
    str += `<input name='${key}' value='${data[key]}' type="hidden" />`;
  }
  const form = document.createElement("form");
  form.action = url;
  form.method = method;
  form.target = "_blank";
  form.style.display = "none";
  document.body.appendChild(form);
  form.innerHTML = str;
  form.submit();
  document.body.removeChild(form);
};
// 空图片方法
Vue.prototype.$addEmptyImg = dom => {
  dom.removeAttribute("_echarts_instance_");
  dom.innerHTML =
    '<div style="width: 100%;height: 100%;text-align: center;"><img src="./public/img/empty.png" style="max-width: 100%;padding-top: 40px;"/></div>';
};
// 数据限制整数
Vue.prototype.$numFormat = data => {
  // zero  第一位是否可以是0
  const { num = "" } = data;
  const str = String(num);
  if (str.length === 1) {
    return str.replace(/[^1-9]/g, "");
  } else {
    return str.replace(/\D/g, "");
  }
};

const vNumFunc = (el, binding, vnode) => {
  const reg = /[^0-9]/g;
  function removeZero(e) {
    if (Object.prototype.toString.call(binding.value) === "[object Object]") {
      // 对象形式
      // 判断min和max
      const { min = -Infinity, max = Infinity } = binding.value;
      if (e.target.value - 0 > max) {
        e.target.value = max;
      }
      if (e.target.value !== "" && e.target.value - 0 < min) {
        e.target.value = min >= 0 ? min : 0;
      }
      vnode.child.$emit("input", e.target.value);
    } else {
      if (Number(binding.expression) === 0) {
        if (e.target.value.slice(0, 1) === "0") {
          e.target.value = e.target.value.slice(1);
          vnode.child.$emit("input", e.target.value);
        }
      }
    }
  }
  // const reg = /[0-9\.]/
  el.onkeypress = function(e) {
    const code = e.charCode;
    // console.log(String.fromCharCode(code))
    if (code !== 0) {
      if (!String.fromCharCode(code).match(/[0-9]/)) {
        return false;
      }
    }
  };
  el.onmousewheel = function(e) {
    const evt = e || window.event;
    if (evt.preventDefault) {
      // Firefox
      evt.preventDefault();
      evt.stopPropagation();
    } else {
      // IE
      evt.cancelBubble = true;
      evt.returnValue = false;
    }
    return false;
  };
  el.onDOMMouseScroll = function(e) {
    const evt = e || window.event;
    if (evt.preventDefault) {
      // Firefox
      evt.preventDefault();
      evt.stopPropagation();
    } else {
      // IE
      evt.cancelBubble = true;
      evt.returnValue = false;
    }
    return false;
  };
  el.onchange = function(e) {
    e.target.value = e.target.value.replace(reg, "");
    vnode.child.$emit("input", e.target.value);
    removeZero(e);
  };
  el.addEventListener("textInput", function(e) {
    e.target.value = e.target.value.replace(reg, "");
    vnode.child.$emit("input", e.target.value);
    removeZero(e);
  });
  el.onkeyup = function(e) {
    // https://www.cnblogs.com/iagw/p/5818263.html
    // 之所以下方这样写，是因为在搜狗浏览器  8.5.10.31270版本上会出现光标不可移动的问题
    const val = e.target.value.replace(reg, "");
    if (val !== e.target.value) {
      e.target.value = val;
      vnode.child.$emit("input", e.target.value);
    }
    removeZero(e);
  };
};
Vue.directive("num", {
  bind: vNumFunc,
  update: vNumFunc
});
// blur方法去掉前后空格
const vBlurTrimFunc = (el, binding, vnode) => {
  const textarea = el.querySelector("textarea");
  const text = el.querySelector("input[type='text']");
  const num = el.querySelector("input[type='number']");
  const func = function(e) {
    const val = e.target.value;
    e.target.value = String(val).trim();
    vnode.child.handleBlur();
    vnode.child.$emit("input", e.target.value);
  };
  textarea && textarea.addEventListener("blur", func);
  text && text.addEventListener("blur", func);
  num && num.addEventListener("blur", func);
};
Vue.directive("blurTrim", {
  bind: vBlurTrimFunc,
  update: vBlurTrimFunc
});
// 删除提示
let _confirm=Element.MessageBox.confirm
Vue.prototype.confirmFunc = (pram) => {
  let { msg = "", title = "提示" } = pram;
  return new Promise((resolve, reject) => {
    _confirm(msg, title, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        resolve();
      })
      .catch(() => {
        reject("取消");
      });
  });
}

Vue.config.productionTip = false;
// 取消请求的对象
window.axiosPromiseArr = [];

// import echarts from 'echarts'
if (window.echarts) {
  Vue.prototype.$echarts = echarts; // eslint-disable-line
}
Vue.prototype.globalMapKey = window.globalMapKey;
function deepMenu(list, arr) {
  // eslint-disable-line
  list.map(item => {
    if (
      arr.findIndex(vo => {
        return item.route === vo.route;
      }) === -1
    ) {
      arr.push(item);
    }
    if (item.children && item.children.length) {
      deepMenu(item.children, arr);
    }
  });
}
export function initApp(params) {
  const { store, router, routeObj, layout, App } = params;
  window._VUE_INSTANCE = new Vue({
    el: "#app",
    router,
    store,
    render: h => h(App)
  });
  store.dispatch("user/getMenu", {
      appKey: window.$appKey
    }, {
      // 设置报错不提示
      notMessage: false
    })
    .then(res => {
      try {
        let list = []; // eslint-disable-line
        deepMenu(res.data, list);
        let asyncRouteList = []; // eslint-disable-line
        for (const item of list) {
          if (!routeObj[item.route] || !item.route) {
            continue;
          }
          asyncRouteList.push({
            path: item.route,
            component: layout,
            children: [
              {
                path: item.route,
                component: routeObj[item.route]["component"],
                name: routeObj[item.route]["name"],
                meta: { title: item.name, icon: item.icon, noCache: false }
              }
            ]
          });
        }
        router.addRoutes(asyncRouteList);
      } catch (error) {
        console.log(error);
      }

    }).catch(() => {
      window._VUE_INSTANCE = new Vue({
        el: "#app",
        router,
        store,
        render: h => h(App)
      });
    });
}
